package com.kfm.servlet;

import com.kfm.util.Constant;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

@WebServlet("/image-list")
public class ImageListServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");

        PrintWriter writer = resp.getWriter();

        writer.write("<table width='700px' border='1px'>");
        // 写表头
        String thead = """
                <tr>
                    <th>序号</th>
                    <th>文件名</th>
                    <th>操作</th>
                </tr>
                """;
        writer.write(thead);

        // tbody
        File file = new File(Constant.UPLOAD_PATH);  // d://temp/upload
        // 子文件
        File[] files = file.listFiles();



        int count = 1;
        for (File child : files){
            // child = d://temp/upload/20231017
            if (child.isDirectory()){ // 是文件夹
                // 添加一级子目录
                String path = child.getName(); // 20231017
                File[] files1 = child.listFiles(); // 所有文件
                for (File f : files1){
                    String body = tableBody(f, path, count ++);
                    writer.write(body);
                }
            }
        }

        writer.write("</table>");
    }

    public String tableBody(File file, String path, Integer count) throws UnsupportedEncodingException {
        String url = "download?";
        String name = file.getName();
        // download?file=20231017/43edb98809224e9a9a83c423f6f3b837.jpg
        String visitable = path + File.separator + name;
        String visit = url + "file=" + URLEncoder.encode(visitable, "utf-8");
        String body = """
                                <tr>
                                    <td>%d</td>
                                    <td>%s</td>
                                    <td>
                                        <a href='%s'>访问链接</a>
                                        <a href='%s'>下载链接</a>
                                    </td>
                                </tr>
                            """.formatted(count, name,
                visit, visit + "&download");
        return body;
    }
}
